package klog

import (
	"math"
	"sync"
)

const (
	MINIMAL_RATE float64 = 1e-8
	MAX_COUNT    float64 = 1 << 30
)

type DownSampler struct {
	rate    float64
	divider float64
	counter float64
	lock    sync.Mutex
}

func NewDownSampler(rate float64) *DownSampler {
	if rate < MINIMAL_RATE {
		rate = MINIMAL_RATE
	}
	if rate > 1 {
		rate = 1
	}
	return &DownSampler{
		rate:    rate,
		divider: 1 / rate,
		counter: -1,
		lock:    sync.Mutex{},
	}

}

func (o *DownSampler) Ok() bool {
	if o.rate == 1 {
		return true
	}

	o.lock.Lock()
	defer o.lock.Unlock()

	o.counter += 1
	if o.counter == MAX_COUNT {
		o.counter = 0
	}
	return math.Mod(o.counter, o.divider) < 1
}
